var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    issuccessMask: false,
    // 发车遮罩层
    isdispatcCar: false,
    ypage: false,
    isdelorder: false,

  },
  // 删除醒目
  delorder() {
    let t = this
    wx.showModal({
      content: '是否要删除该项目',
      confirmColor: "#D6000F",
      success(res) {
        if (res.confirm) {
          t.delProjectOrder()
        } else if (res.cancel) {

        }
      }
    })
  },
  // 隐藏删除遮罩层
  Hidedelorder() {
    this.setData({
      isdelorder: false
    })
    wx.setStorageSync('istab', true)
    wx.navigateBack({
      delta: 1,
    })
  },
  // 删除项目
  delProjectOrder(e) {

    let t = this
    wx.showLoading({
      title: '加载中。。。', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'delProjectOrder',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        orderId: t.data.orderId,
        token: t.data.token
      },
      success: res => {
        wx.hideLoading();

        if (res.data.result == 0) {
          t.setData({
            isdelorder: true
          })
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          t.setData({
            token: app.token()
          })
        }







      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })






  },
  // 修改驳回订单
  Modifyreject() {
    wx.navigateTo({
      url: '/shopowner/pages/previewOrder/previewOrder?todo=Modifyreject&&orderObj=' + JSON.stringify(this.data.orderObj),
    })
  },

  // 查看图片
  priview(e) {

    let current = e.currentTarget.dataset.current
    let urls = e.currentTarget.dataset.urls
    wx.previewImage({
      urls: urls,
      current: current
    })
  },



  // 店长创建编辑项目
  saveProjectOrder() {
    let t = this
    wx.showLoading({
      title: '加载中',

      mask: true //显示透明蒙层 防止触摸穿透
    })
    let operateType
    if (app.globalData.identity == 5) {
      operateType = 2;

    } else {
      operateType = 2;
    }
    wx.request({
      url: app.globalData.Interfaceurl + 'saveProjectOrder',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        token: t.data.token,
        orderId: t.data.orderObj.orderId,
        operateType: operateType,
        designerId: t.data.orderObj.designerId,
        customerName: t.data.orderObj.customerName,
        customerPhone: t.data.orderObj.customerPhone,
        projectProvince: t.data.orderObj.projectProvince,
        projectCity: t.data.orderObj.projectCity,
        projectArea: t.data.orderObj.projectArea,
        projectAddress: t.data.orderObj.projectAddress,
        projectName: t.data.orderObj.projectName,
        projectSize: t.data.orderObj.projectSize,
        projectLayout: t.data.orderObj.projectLayout,
        projectCover: t.data.orderObj.projectCover.join(","),
        bptContract: t.data.orderObj.bptContract.join(","),
        bptAmount: t.data.orderObj.price,
        bptDepositFlag: t.data.orderObj.bptDepositFlag,
        bptDeposit: t.data.orderObj.bptDeposit,
        bptDepositProof: t.data.orderObj.bptDepositProof.join(","),
        bptBalance: t.data.orderObj.bptBalance,
        remarks: t.data.orderObj.projectDescribe
      },
      success: res => {
        wx.hideLoading()
        if (res.data.result == 0) {
          t.setData({
            issuccessMask: true
          })
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          t.setData({
            token: app.token()
          })
        }
      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },
  // 修改订单
  gomodifyOrder(e) {
    let to = e.currentTarget.dataset.to
    if (this.data.todo == 'ceateOrder' || this.data.todo == 'Modifyreject' || this.data.todo == 'jiaju') {
      if (to == "addMembers") {
        wx.navigateTo({
          url: "/shopowner/pages/addpeople/addpeople?todo=modifyOrder&&orderObj=" + JSON.stringify(this.data.orderObj),
        })
      } else if (to == "PropertyInformation") {
        wx.navigateTo({
          url: "/shopowner/pages/addProperty/addProperty?todo=modifyOrder&&orderObj=" + JSON.stringify(this.data.orderObj),
        })
      } else if (to == "preview") {

        wx.navigateTo({
          url: "/shopowner/pages/orderAttachment/orderAttachment?todo=modifyOrder&&orderObj=" + JSON.stringify(this.data.orderObj),
        })
      } else if (to == "createorder") {
        wx.navigateTo({
          url: "/shopowner/pages/createorder/createorder?todo=modifyOrder&&orderObj=" + JSON.stringify(this.data.orderObj),
        })
      } else if (to == 'previewdepositAttachment') {
        wx.navigateTo({
          url: "/shopowner/pages/depositAttachment/depositAttachment?todo=modifyOrder&&orderObj=" + encodeURIComponent(JSON.stringify(this.data.orderObj))
        })
      }
    }





    if (this.data.todo == 'Delivery') {
      if (to == "predriverview") {
        wx.navigateTo({
          url: "/shopowner/pages/addpeople/addpeople?todo=modifydrivery&&orderObj=" + JSON.stringify(this.data.orderObj)
        })
      } else if (to == "hamal") {
        wx.navigateTo({
          url: "/shopowner/pages/addpeople/addpeople?todo=modifyhamal&&orderObj=" + JSON.stringify(this.data.orderObj)
        })
      } else if (to == "DeliveryPrictrue") {

        wx.navigateTo({
          url: "/shopowner/pages/deliveryList/deliveryList?todo=modifyDelivery&&orderObj=" + JSON.stringify(this.data.orderObj)
        })
      }
    }






    if (this.data.todo == 'design' || this.data.todo == 'previewDeparture') {
      if (to == "addMembers") {
        wx.navigateTo({
          url: "/shopowner/pages/addpeople/addpeople?todo=modifyOrderer&&orderObj=" + JSON.stringify(this.data.orderObj),
        })
      }
    }




  },



  // 上传附件
  upload(arr) {
    return new Promise((reslove, reject) => {

      if (arr.length == 0) {
        reslove([])
        return
      }
      wx.showLoading({
        title: '上传中...', //提示的内容
        mask: true //显示透明蒙层 防止触摸穿透
      })
      let finishFilesList = []
      arr.forEach((item, index) => {
        wx.uploadFile({
          url: app.globalData.Interfaceurl + 'saveFileUpload',
          filePath: item,
          name: 'file',
          formData: {
            userId: app.globalData.userId,

          },
          header: {
            "content-type": "multipart/form-data"
          },
          success: function (res) {

            finishFilesList.push(JSON.parse(res.data).fileUrl)

            if (index >= arr.length - 1) {
              setTimeout(() => {
                wx.hideLoading();
                reslove(finishFilesList)
              }, 500)

            }
          },
          fail: err => {
            return err
          }
        })
      })
    })


  },

  // 立即派单
  binddispatch() {
    if (this.data.orderObj.orderId == '') {
      this.upload(this.data.orderObj.projectCover)
        .then(res => {
          this.data.orderObj.projectCover = res

          this.upload(this.data.orderObj.bptContract)
            .then(res => {
              this.data.orderObj.bptContract = res

              this.upload(this.data.orderObj.bptDepositProof)
                .then(res => {
                  this.data.orderObj.bptDepositProof = res

                  this.saveProjectOrder()
                })
            })
        })
    } else {

      let orderObj = this.data.orderObj
      let nocoverList = this.data.orderObj.projectCover.filter(item => item.indexOf(app.globalData.Imageurl) == -1)
      let uncoverList = this.data.orderObj.projectCover.filter(item => item.indexOf(app.globalData.Imageurl) != -1)
      let newuncoverList = []
      uncoverList.forEach(item => {
        newuncoverList.push(item.replace(app.globalData.Imageurl, ""))
        item.replace(app.globalData.Imageurl, "")
      })
      let nocontractList = this.data.orderObj.bptContract.filter(item => item.indexOf(app.globalData.Imageurl) == -1)
      let uncontractList = this.data.orderObj.bptContract.filter(item => item.indexOf(app.globalData.Imageurl) != -1)
      let newuncontractList = []
      uncontractList.forEach(item => {
        newuncontractList.push(item.replace(app.globalData.Imageurl, ""))
      })
      let nobptDepositProof = this.data.orderObj.bptDepositProof.filter(item => item.indexOf(app.globalData.Imageurl) == -1)
      let unbptDepositProof = this.data.orderObj.bptDepositProof.filter(item => item.indexOf(app.globalData.Imageurl) != -1)
      let newunbptDepositProof = []
      unbptDepositProof.forEach(item => {
        newunbptDepositProof.push(item.replace(app.globalData.Imageurl, ""))
      })

      console.log("改改1")
      this.upload(nocoverList)
        .then(res => {
          orderObj.projectCover = [...res, ...newuncoverList]
          console.log(res)

          this.upload(nocontractList)
            .then(res => {

              orderObj.bptContract = [...res, ...newuncontractList]
              console.log(nobptDepositProof)
              this.upload(nobptDepositProof)
                .then(res => {
                  orderObj.bptDepositProof = [...res, ...newunbptDepositProof]
                  this.setData({
                    orderObj: orderObj
                  })
                  console.log("改改3")
                  this.saveProjectOrder()
                })
            })
        })
    }
  },
  // 发车
  dispatcCar() {
    let orderObj = this.data.orderObj
    let t = this
    this.upload(orderObj.productList)
      .then(res => {
        orderObj.productList = res
        this.upload(orderObj.packAtlas)
          .then(res => {
            orderObj.packAtlas = res
            this.setData({
              orderObj: orderObj
            })

            this.saveOrderDeliver()
          })
      })
  },
  // 选择产品图
  bindproductMap() {
    wx.navigateTo({
      url: '/shopowner/pages/productMap/productMap?id=' + this.data.orderId,
    })
  },

  HidedispatcCar() {
    this.setData({
      isdispatcCar: false,
      todo: 'previewDeparture'
    })
    wx.setStorageSync('istab', true)
  },
  goorderdectio() {

    let pages = getCurrentPages();
    console.log(pages.length)
    if (pages.length == 6) {
      let prevPage = pages[pages.length - 5]; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。\\
      prevPage.getOrderDetails()
      prevPage.setData({
        todo: ''
      })
      wx.navigateBack({
        delta: 4,
      })
    } else {
      wx.navigateTo({
        url: '/pages/projectDetails/projectDetails?orderId=' + this.data.orderId,
      })
    }
  },
  // 隐藏遮罩层
  HidesuccessMask() {
    this.setData({
      issuccessMask: false,
      todo: 'previewDeparture'
    })
    app.globalData.tabindex = 1
    wx.setStorageSync('istab', true)
    wx.switchTab({
      url: '/pages/project/project',
    })

  },

  fakeCallback() {},

  // 项目详情接口
  getOrderDetails(orderId) {
    let t = this
    wx.showLoading({
      title: '加载中。。。', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'getOrderDetails',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        // userId: 1569562832576524288,
        orderId: t.data.orderId,
      },
      success: res => {

        let orderObj = this.data.orderObj
        let projectOrder = res.data.projectOrder

        orderObj.projectCity = projectOrder.projectCity
        orderObj.projectName = projectOrder.projectName
        orderObj.projectLayout = projectOrder.projectLayout
        orderObj.projectSize = projectOrder.projectSize
        orderObj.projectArea = projectOrder.projectArea
        orderObj.customerName = projectOrder.customerName
        orderObj.customerPhone = projectOrder.customerPhone
        orderObj.projectAddress = projectOrder.projectAddress
        orderObj.projectName = projectOrder.projectName
        orderObj.projectProvince = projectOrder.projectProvince
        orderObj.orderId = projectOrder.id
        orderObj.projectCover = projectOrder.projectCover
        orderObj.bptDepositFlag = projectOrder.bptDepositFlag

        orderObj.projectDescribe = projectOrder.remarks
        console.log(orderObj.projectDescribe)


        if (res.data.adviser && res.data.adviser.id) {
          orderObj.paidan = res.data.adviser
        } else {
          orderObj.paidan = res.data.shopowner

        }




        if (t.data.todo == 'design' || t.data.todo == 'rejected' || t.data.todo == 'jiaju') {
          if (res.data.designer == '') {
            orderObj.designerId = ''
            orderObj.designerObj = {}
          } else {

            orderObj.designerId = res.data.designer.id
            orderObj.designerObj = res.data.designer
          }

          if (projectOrder.projectCover == '') {
            orderObj.projectCover = []
          } else {
            orderObj.projectCover = [app.globalData.Imageurl + projectOrder.projectCover]
          }


          orderObj.price = projectOrder.bptAmount
          orderObj.bptContract = projectOrder.bptContract.split(",").map(item => app.globalData.Imageurl + item)
          orderObj.bptDeposit = projectOrder.bptDeposit
          orderObj.bptDepositProof = projectOrder.bptDepositProof.split(",").map(item => app.globalData.Imageurl + item)
          orderObj.bptBalance = projectOrder.bptBalance
        }



        if (res.data.deliverList.length != 0) {

          let deliverList = res.data.deliverList
          console.log(deliverList)
          orderObj.driverName = deliverList[0].driverName
          orderObj.driverMobile = deliverList[0].driverMobile
          orderObj.workerName = deliverList[0].workerName
          orderObj.workerMobile = deliverList[0].workerMobile
          orderObj.leaveDate = deliverList[0].leaveDate
          orderObj.serviceDate = deliverList[0].serviceDate
          orderObj.deliverExplain = deliverList[0].deliverExplain
          let productList = deliverList[0].deliverProductList.split(",").map(item => app.globalData.Imageurl + item)
          let packAtlas = deliverList[0].packAtlas.split(",").map(item => app.globalData.Imageurl + item)

          console.log(orderObj)
          this.setData({
            productList: productList,
            packAtlas: packAtlas
          })
        }
        t.setData({
          orderObj: orderObj
        })
        wx.hideLoading();
        if (t.data.officialAccount ) {
          if(res.data.projectOrder.designDate != ''&&t.data.todo=='design'){
            wx.redirectTo({
              url: '/pages/projectDetails/projectDetails?orderId='+t.data.orderId,
            })
          }
         
          if(res.data.projectOrder.projectStatus==1 &&t.data.todo=='rejected'){
            wx.redirectTo({
              url: '/pages/projectDetails/projectDetails?orderId='+t.data.orderId,
            })
          }
        }else{
          t.setData({
            isloadcomplete:false
          })
        }
      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },



  // 18.上传配送清单

  saveOrderDeliver() {
    let t = this
    wx.showLoading({
      title: '加载中。。。', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'saveOrderDeliver',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        // userId: 1569562832576524288,
        orderId: t.data.orderId,
        token: t.data.token,
        productList: t.data.orderObj.productList.join(","),
        packAtlas: t.data.orderObj.packAtlas.join(","),
        deliverExplain: t.data.orderObj.deliverExplain,
        leaveDate: t.data.orderObj.leaveDate,
        serviceDate: t.data.orderObj.serviceDate,
        driverName: t.data.orderObj.driverName,
        driverMobile: t.data.orderObj.driverMobile,
        workerName: t.data.orderObj.workerName,
        workerMobile: t.data.orderObj.workerMobile,
        licensePlate: t.data.orderObj.licensePlate
      },
      success: res => {
        wx.hideLoading()
        if (res.data.result == 0) {
          this.setData({
            isdispatcCar: true,
            ypage: true
          })
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          t.setData({
            token: app.token()
          })
        }
      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    if (!app.globalData.isonLaunch) {
      app.wxlogin()
        .then(res => {
          this.setData({
            token: app.token(),
            identity: app.globalData.identity
          })


          if (options.orderObj) {
            this.setData({
              orderObj: JSON.parse(options.orderObj)
            })
          }
          if (options.todo) {
            this.setData({
              todo: options.todo
            })
          }
          if (options.todo == 'Delivery') {
            this.setData({
              orderId: options.orderId,
              productList: this.data.orderObj.productList,
              packAtlas: this.data.orderObj.packAtlas,

            })
            this.getOrderDetails()
          }
          if (options.todo == 'design' || options.todo == 'rejected') {
            this.setData({
              orderObj: {},
              orderId: options.orderId
            })
            this.getOrderDetails()
          }
          if (options.todo == 'previewDeparture') {
            this.setData({
              orderId: options.orderId,
              orderObj: {}
            })
            this.getOrderDetails()
          }

          if (options.todo == 'jiaju') {
            this.setData({
              orderId: options.orderId,
              orderObj: {}
            })
            this.getOrderDetails()
          }

        })
    } else {
      this.setData({
        token: app.token(),
        identity: app.globalData.identity
      })


      if (options.orderObj) {
        this.setData({
          orderObj: JSON.parse(options.orderObj)
        })
      }
      if (options.todo) {
        this.setData({
          todo: options.todo
        })
      }
      if (options.todo == 'Delivery') {
        this.setData({
          orderId: options.orderId,
          productList: this.data.orderObj.productList,
          packAtlas: this.data.orderObj.packAtlas,

        })
        this.getOrderDetails()
      }
      if (options.todo == 'design' || options.todo == 'rejected') {
        this.setData({
          orderObj: {},
          orderId: options.orderId
        })
        this.getOrderDetails()
      }
      if (options.todo == 'previewDeparture') {
        this.setData({
          orderId: options.orderId,
          orderObj: {}
        })
        this.getOrderDetails()
      }

      if (options.todo == 'jiaju') {
        this.setData({
          orderId: options.orderId,
          orderObj: {}
        })
        this.getOrderDetails()
      }
    }

    if (options.officialAccount) {
      this.setData({
        officialAccount: options.officialAccount,
        ypage: true,
        isloadcomplete:true
      })
    }





  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onPageScroll(e) {

    this.setData({
      bigscrooltop: e.scrollTop
    })

  }
})